package TangramBase;

import TangramCore.Database;
import TangramCore.Skladacka;
import java.awt.*;
import java.awt.event.*;
import java.util.Collections;
import java.util.Vector;

import javax.swing.*;
import javax.swing.tree.*;

public class MassDescriptionFrame extends JFrame implements ItemListener, ActionListener, DocumentWindow, Database.DatabaseChangeListener{
	static final long serialVersionUID = 24362462L;
	
	private JMenuItem mniThis = null;
    private int iWindow = -1;

    TangramFrame frmDatabase;
    Database database;
    Skladacka skl;
    Database.ObrazecData od;
    Vector<String> remKeywords;
    
    private static final int ID_MASSAPPLY=24, ID_MASSOK=25, ID_MASSCANCEL=26;
            
    Vector<String> allKeys, selKeysAdd, selKeysRemove;
    JTextField txtName = new JTextField();
    JTextArea txtDescription = new JTextArea();
    JTextField txtAuthor = new JTextField();
    JTextField txtDate = new JTextField();
    JCheckBox chkName = new JCheckBox("set name");
    JCheckBox chkDescription = new JCheckBox("set description",true);
    JCheckBox chkAuthor = new JCheckBox("set author");
    JCheckBox chkDate = new JCheckBox("set date");
    JCheckBox chkRemoveAll = new JCheckBox("remove all keywords");
    
    JTree treeKeywords;
    ActionListener updateDate = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            now.setTime(System.currentTimeMillis());
            txtDate.setText(df.format(now));
        }
    };
    
    JComboBox cmbDate;
    JList lstAllKeywords = new JList();
    JList lstKeywordsAdd = new JList();
    JList lstKeywordsRemove = new JList();
    JButton cmdOK = new JButton("OK");
    JButton cmdApply = new JButton("Apply");
    JButton cmdCancel = new JButton("Cancel");
    
    public MassDescriptionFrame(TangramFrame tf, Database d) {
        frmDatabase = tf;
        database = d;
        skl = database.getActSet();
        setTitle();        
        
        treeKeywords = new JTree(frmDatabase.treeModel);
        
        Font font = txtName.getFont();
        JPanel pnlWest = new JPanel(new BorderLayout()); //GridLayout(3,1));
        //pnlWest.setBackground(Color.white);
        
        JPanel pnlName = new JPanel(new BorderLayout());
        //pnlName.setBackground(Color.white);
        pnlName.setBorder(BorderFactory.createTitledBorder("Name"));
        chkName.setFont(font);
        //chkName.setOpaque(false);
        pnlName.add(chkName, BorderLayout.NORTH);
        pnlName.add(txtName,BorderLayout.CENTER);
        
        JPanel pnlAll = new JPanel(new BorderLayout());//new GridLayout(4,1));
        //pnlAll.setBackground(Color.white);
        pnlAll.add(pnlName,BorderLayout.NORTH);
        
        JPanel pnlDescr = new JPanel(new BorderLayout());
        //pnlDescr.setBackground(Color.white);
        pnlDescr.setBorder(BorderFactory.createTitledBorder("Description"));
        chkDescription.setFont(font);
        //chkDescription.setOpaque(false);
        pnlDescr.add(chkDescription, BorderLayout.NORTH);
        txtDescription.setBorder(txtName.getBorder());
        txtDescription.setPreferredSize(new Dimension(275,100));
        pnlDescr.add(txtDescription,BorderLayout.CENTER);
        pnlAll.add(pnlDescr,BorderLayout.CENTER);
        
        JPanel pnlAllSouth = new JPanel(new GridLayout(2,1));
        //pnlAllSouth.setBackground(Color.white);
        JPanel pnlAuthor = new JPanel(new BorderLayout());
        //pnlAuthor.setBackground(Color.white);
        pnlAuthor.setBorder(BorderFactory.createTitledBorder("Author"));
        chkAuthor.setFont(font);
        //chkAuthor.setOpaque(false);
        pnlAuthor.add(chkAuthor, BorderLayout.NORTH);
        pnlAuthor.add(txtAuthor,BorderLayout.CENTER);
        pnlAllSouth.add(pnlAuthor);
        
        JPanel pnlDate = new JPanel(new BorderLayout());
        //pnlDate.setBackground(Color.white);
        pnlDate.setBorder(BorderFactory.createTitledBorder("Date"));
        chkDate.setFont(font);
        //chkDate.setOpaque(false);
        pnlDate.add(chkDate, BorderLayout.NORTH);
        JPanel pnlDateText = new JPanel(new BorderLayout());
        //pnlDateText.setBackground(Color.white);
        now.setTime(System.currentTimeMillis());
        txtDate.setText(df.format(now));
        pnlDateText.add(txtDate,BorderLayout.CENTER);
        cmbDate = new JComboBox(cmbItems);
        cmbDate.addItemListener(this);
        //cmbDate.setBackground(Color.white);
        cmbDate.setFont(font);
        pnlDateText.add(cmbDate,BorderLayout.EAST);
        pnlDate.add(pnlDateText,BorderLayout.CENTER);
        pnlAllSouth.add(pnlDate);
        
        txtDate.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){DescriptionFrame.validateDate(txtDate,cmbDate,false);}});
        txtDate.addFocusListener(new FocusAdapter(){public void focusLost(FocusEvent e){DescriptionFrame.validateDate(txtDate,cmbDate,false);}});
        
        pnlAll.add(pnlAllSouth,BorderLayout.SOUTH);
        pnlWest.add(pnlAll,BorderLayout.CENTER);
        
        selKeysAdd = new Vector<String>();
        selKeysRemove = new Vector<String>();
        
        treeKeywords.setBorder(txtName.getBorder());
        MouseListener mlSel = new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getButton()==MouseEvent.BUTTON3) {
                    Vector<String> sel;
                    JList lst;
                    if(e.isShiftDown()){
                        sel = selKeysRemove;
                        lst = lstKeywordsRemove;
                    } else{
                        sel = selKeysAdd;
                        lst = lstKeywordsAdd;
                    }
                    TreePath treePath = treeKeywords.getPathForLocation(e.getPoint().x,e.getPoint().y);
                    if(treePath==null)
                        return;
                    Object obj[] = treePath.getPath();
                    for(int i=1; i<obj.length; i++){
                        String s = ((DefaultMutableTreeNode) obj[i]).toString();
                        if(!sel.contains(s))
                            sel.add(s);
                    }
                    Collections.<String>sort(sel);
                    lst.setListData(sel);
                }
            }
        };
        
        treeKeywords.addMouseListener(mlSel);
        //treeKeywords.setToggleClickCount(1);
        JScrollPane scrAll = new JScrollPane(treeKeywords);
        scrAll.setBorder(BorderFactory.createTitledBorder("Available keywords"));
        //scrAll.setOpaque(false);
        scrAll.setPreferredSize(new Dimension(200,200));
        
        lstKeywordsAdd.setFont(font);
        lstKeywordsAdd.setBorder(txtName.getBorder());
        MouseListener mlDesel = new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int index = lstKeywordsAdd.locationToIndex(e.getPoint());
                    if(index>-1){
                        selKeysAdd.remove(index);
                        lstKeywordsAdd.setListData(selKeysAdd);
                    }
                }
            }
        };
        lstKeywordsAdd.addMouseListener(mlDesel);
        
        JScrollPane scrSelAdd = new JScrollPane(lstKeywordsAdd);
        scrSelAdd.setBorder(BorderFactory.createTitledBorder("Add keywords"));
        //scrSelAdd.setOpaque(false);
        scrSelAdd.setPreferredSize(new Dimension(150,200));
        
        lstKeywordsRemove.setFont(font);
        lstKeywordsRemove.setBorder(txtName.getBorder());
        MouseListener mlDesel2 = new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int index = lstKeywordsRemove.locationToIndex(e.getPoint());
                    if(index>-1){
                        selKeysRemove.remove(index);
                        lstKeywordsRemove.setListData(selKeysRemove);
                    }
                }
            }
        };
        lstKeywordsRemove.addMouseListener(mlDesel2);
        
        JPanel pnlSelRemove = new JPanel(new BorderLayout());
        //pnlSelRemove.setBackground(Color.white);
        pnlSelRemove.setBorder(BorderFactory.createTitledBorder("Remove keywords"));
        JScrollPane scrSelRemove = new JScrollPane(lstKeywordsRemove);
        //scrSelRemove.setOpaque(false);
        scrSelRemove.setPreferredSize(new Dimension(150,200));
        scrSelRemove.setBorder(BorderFactory.createEmptyBorder());
        chkRemoveAll.setFont(font);
        //chkRemoveAll.setOpaque(false);
        pnlSelRemove.add(chkRemoveAll,BorderLayout.NORTH);
        pnlSelRemove.add(scrSelRemove,BorderLayout.CENTER);
        
        JPanel pnlSel = new JPanel(new GridLayout(1,2));
        //pnlSel.setBackground(Color.white);
        pnlSel.add(scrSelAdd);
        pnlSel.add(pnlSelRemove);
        
        JPanel pnlSouth = new JPanel(new FlowLayout());
        //pnlSouth.setBackground(Color.white);
        //cmdApply.setActionCommand(String.valueOf(tf.ID_MASSAPPLY));
        //cmdApply.addActionListener(tf);
        cmdCancel.setActionCommand(String.valueOf(ID_MASSCANCEL));
        cmdCancel.addActionListener(this);
        cmdOK.setActionCommand(String.valueOf(ID_MASSOK));
        cmdOK.addActionListener(this);
        //pnlSouth.add(cmdApply);
        pnlSouth.add(cmdOK);
        pnlSouth.add(cmdCancel);
        
        Container pane = getContentPane();
        pane.add(pnlWest,BorderLayout.WEST);
        pane.add(scrAll,BorderLayout.CENTER);
        pane.add(pnlSel,BorderLayout.EAST);
        pane.add(pnlSouth,BorderLayout.SOUTH);
        
        int w = 825, h = 500;
        setSize(w,h);
        TangramFrame.centerOnScreen(this);
        setResizable(false);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {public void windowClosing(WindowEvent e){cmdCancel.doClick();}});
    }
    
    public boolean apply(Database.ObrazecData od){
        od.datum = DescriptionFrame.validateDate(txtDate,cmbDate,true);
        if(od.datum == null)
            return false;
        od.nazev = chkName.isSelected() ? txtName.getText() : null;
        od.popis = chkDescription.isSelected() ? txtDescription.getText() : null;
        od.autor = chkAuthor.isSelected() ? txtAuthor.getText() : null;
        if(od.datum != null)  //zvazit
            txtDate.setText(df.format(od.datum));
        cmbDate.setSelectedIndex(0);
        if(!chkDate.isSelected())
            od.datum = null;
        od.keywords = selKeysAdd.isEmpty() ? null : new Vector<String>(selKeysAdd);
        
        ///TODO ???
        /*Vector<String> ret;
        if(chkRemoveAll.isSelected())
            ret = new Vector<String>();
        else
            ret = selKeysRemove.isEmpty() ? null : new Vector<String>(selKeysRemove);
        */
        selKeysAdd.clear();  //zvazit
        lstKeywordsAdd.setListData(selKeysAdd);
        selKeysRemove.clear();
        lstKeywordsRemove.setListData(selKeysRemove);
        return true;
    }
    
    /*public boolean isValid(){
        return isValid;
    }*/
    
    /*public void changeKeywords(DescriptionFrame dsf){
        treeKeywords.setModel(dsf.treeKeywords.getModel());
    }*/
    
    public void itemStateChanged(ItemEvent e){
        DescriptionFrame.setComboItem(e,updateDate,txtDate);
    }
    
    @Override
    public void setVisible(boolean jak){
        if(cmbDate.getSelectedIndex()==2){
            if(jak == false)
                DescriptionFrame.removeTimerListener(updateDate);
            else
                DescriptionFrame.addTimerListener(updateDate);
        }
        super.setVisible(jak);
    }
    
    public void actionPerformed(ActionEvent e){
        int actionID = Integer.parseInt(e.getActionCommand());
        switch (actionID) {
            case ID_MASSOK: case ID_MASSAPPLY:
                setEnabled(false);
                od = new Database.ObrazecData(skl);
                if(apply(od)){
                    frmDatabase.mass(remKeywords, od);
                    if(actionID == ID_MASSOK)
                        showDocument(false);
                }
                setEnabled(true);
            case ID_MASSCANCEL:
                showDocument(false);
                break;
        }
    }
    private void setTitle(){
        super.setTitle("Mass Description" + sDash + skl.nazev + sLFigureBracket + database.selectedCount() + " figures selected" + sRFigureBracket);
        setMenuItemText();
    }
    
    private void setMenuItemText(){
        if(mniThis != null)
            mniThis.setText(sLNumberBracket + iWindow + sRNumberBracket + getTitle());
    }
    
    public void setMenuItem(int i, JMenuItem mni){
        iWindow = i;
        mniThis = mni;
        setMenuItemText();
    }

    public void restoreState(){
        toFront();//setExtendedState(lastState);
    }

    public boolean showDocument(boolean jak){
        boolean ret = jak ? frmDatabase.windowOpened(this):frmDatabase.windowClosed(this);
        setVisible(jak);
        if(jak)
            toFront();
        else
            dispose();
        return ret;
    }
    public boolean databaseChanged(int what, int i){
        setTitle();
        return true;
    }
    public boolean hasChanged(){
        return false;
    }

}
